<?php

/* 清除购物车中过期的数据 */
function clear_cart(){
	$CommonModel	=	new CommonModel();
    /* 取得有效的session */
    $sql 		= 	"SELECT DISTINCT session_id " .
            		"FROM " . 'ybr_cart' . " AS c, " .
                	'ybr_sessions' . " AS s " .
            		"WHERE c.session_id = s.sesskey ";
    $valid_sess = 	$CommonModel->getCol($sql);

    // 删除cart中无效的数据
    $sql = "DELETE FROM " . 'ybr_cart' .
            " WHERE session_id NOT " . db_create_in($valid_sess);
    $CommonModel->query($sql);
}


/**
 * 获得用户的真实IP地址
 *
 * @access  public
 * @return  string
 */
function real_ip(){
    static $realip = NULL;
    if ($realip !== NULL){
        return $realip;
    }
    if (isset($_SERVER)){
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])){
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);

            /* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
            foreach ($arr AS $ip){
                $ip = trim($ip);
                if ($ip != 'unknown'){
                    $realip = $ip;
                    break;
                }
            }
        }
        elseif (isset($_SERVER['HTTP_CLIENT_IP'])){
            $realip = $_SERVER['HTTP_CLIENT_IP'];
        }
        else{
            if (isset($_SERVER['REMOTE_ADDR'])){
                $realip = $_SERVER['REMOTE_ADDR'];
            }
            else{
                $realip = '0.0.0.0';
            }
        }
    }
    else{
        if (getenv('HTTP_X_FORWARDED_FOR')){
            $realip = getenv('HTTP_X_FORWARDED_FOR');
        }
        elseif (getenv('HTTP_CLIENT_IP')){
            $realip = getenv('HTTP_CLIENT_IP');
        }
        else{
            $realip = getenv('REMOTE_ADDR');
        }
    }

    preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
    $realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';

    return $realip;
}

/**
 * 递归方式的对变量中的特殊字符进行转义
 *
 * @access  public
 * @param   mix     $value
 *
 * @return  mix
 */
function addslashes_deep($value){
    if (empty($value)){
        return $value;
    }
    else{
        return is_array($value) ? array_map('addslashes_deep', $value) : addslashes($value);
    }
}


/**
 * 清除缓存
 * Enter description here ...
 * 
 */
function clear_cache(){
	$dirname = './admin/Runtime/';
	@mkdir($dirname,0777,true); // 赋予该目录最大权限
  	rmdirr($dirname);
}	
function rmdirr($dirname) {
  	if (!file_exists($dirname)) {
  		return false;
  	}
  	if (is_file($dirname) || is_link($dirname)) {
   		return unlink($dirname);
  	}
  	$dir = dir($dirname);
  	if($dir){
   		while (false !== $entry = $dir->read()) {
			if ($entry == '.' || $entry == '..') {
	 			continue;
			}
			//递归
			rmdirr($dirname . DIRECTORY_SEPARATOR . $entry);
	   }
  	}
  	$dir->close();
 	return rmdir($dirname);
}




/**
 * 取得商品最终使用价格
 *
 * @param   string  $goods_id      商品编号
 * @param   string  $goods_num     购买数量
 * @param   boolean $is_spec_price 是否加入规格价格
 * @param   mix     $spec          规格ID的数组或者逗号分隔的字符串
 *
 * @return  商品最终购买价格
 */
function get_final_price($goods_id, $goods_num = '1', $is_spec_price = false, $spec = array()){
	
	$CommonModel		=	new CommonModel();
	
    $final_price   		= 	'0'; //商品最终购买价格
    $volume_price  		= 	'0'; //商品优惠价格
    $promote_price 		= 	'0'; //商品促销价格
    $user_price    		= 	'0'; //商品会员价格

    //取得商品优惠价格列表
    $price_list   		= 	get_volume_price_list($goods_id, '1');

    if (!empty($price_list)){
        foreach ($price_list as $value){
            if ($goods_num >= $value['number']){
                $volume_price 		= 	$value['price'];
            }
        }
    }
    
    //处理非会员折扣的价格
    if(empty($_SESSION['discount'])){
    	$_SESSION['discount']	=	1;
    }    
    //取得商品促销价格列表
    //取得商品信息
    $sql 				= 	"SELECT g.promote_price, g.promote_start_date, g.promote_end_date, ".
                			"IFNULL(mp.user_price, g.shop_price * '" . $_SESSION['discount'] . "') AS shop_price ".
				           	" FROM " . 'ybr_goods' . " AS g ".
				           	" LEFT JOIN " . 'ybr_member_price' . " AS mp ".
				            "ON mp.goods_id = g.goods_id AND mp.user_rank = '" . $_SESSION['user_rank']. "' ".
				           	" WHERE g.goods_id = '" . $goods_id . "'" .
				           	" AND g.is_delete = 0";
    
    $goods 				= 	$CommonModel->getRow($sql);
    
    /* 计算商品的促销价格 */
    if ($goods['promote_price'] > 0){
        $promote_price 	= 	bargain_price($goods['promote_price'], $goods['promote_start_date'], $goods['promote_end_date']);
    }
    else{
        $promote_price 	= 	0;
    }
    //取得商品会员价格列表
    $user_price    		= 	$goods['shop_price'];
    //比较商品的促销价格，会员价格，优惠价格
    if (empty($volume_price) && empty($promote_price)){
        //如果优惠价格，促销价格都为空则取会员价格
        $final_price 	= 	$user_price;
    }
    elseif (!empty($volume_price) && empty($promote_price)){
        //如果优惠价格为空时不参加这个比较。
        $final_price 	= 	min($volume_price, $user_price);
    }
    elseif (empty($volume_price) && !empty($promote_price)){
        //如果促销价格为空时不参加这个比较。
        $final_price 	= 	min($promote_price, $user_price);
    }
    elseif (!empty($volume_price) && !empty($promote_price)){
        //取促销价格，会员价格，优惠价格最小值
        $final_price 	= 	min($volume_price, $promote_price, $user_price);
    }
    else{
        $final_price 	= 	$user_price;
    }
	    
    //如果需要加入规格价格
    if ($is_spec_price){
        if (!empty($spec)){
            $spec_price   	= 	spec_price($spec);           
            $final_price 	+= 	$spec_price;
        }
    }

    //返回商品最终购买价格
    return $final_price;
}



/**
 * 判断某个商品是否正在特价促销期
 *
 * @access  public
 * @param   float   $price      促销价格
 * @param   string  $start      促销开始日期
 * @param   string  $end        促销结束日期
 * @return  float   如果还在促销期则返回促销价，否则返回0
 */
function bargain_price($price, $start, $end){
    if ($price == 0){
        return 0;
    }
    else{
        $time = gmtime();
        if ($time >= $start && $time <= $end){
            return $price;
        }
        else{
            return 0;
        }
    }
}


/**
 * 自动返回表名字,兼容带有前缀的,自动去除前缀
 * @param	$tableName 
 * @example	order_info
 * @return	OrderInfo
 * 
 */
function auto_table_name($table){
	/*判断是否存在前缀*/
	$is_exsist_prefix	=	strstr($table,"ybr_"); 
	if($is_exsist_prefix){
		$table			=	str_replace('ybr_', '', $table);
	}
		
	$table_name_array	=	explode("_", $table);
	$tableName			=	'';
	if(count($table_name_array) > 1){
		foreach($table_name_array as $name){
			$tableName 	.=	ucwords($name);
		}
	}else{
		$tableName	=	ucwords( $table_name_array[0]);
	}
	return $tableName;
}



/**
 *  将一个用户自定义时区的日期转为GMT时间戳
 *
 * @access  public
 * @param   string      $str
 *
 * @return  integer
 */
function local_strtotime($str){
	
    $timezone 	= 	isset($_SESSION['timezone']) ? $_SESSION['timezone'] : $GLOBALS['_CFG']['timezone'];
    /**
    * $time = mktime($hour, $minute, $second, $month, $day, $year) - date('Z') + (date('Z') - $timezone * 3600)
    * 先用mktime生成时间戳，再减去date('Z')转换为GMT时间，然后修正为用户自定义时间。以下是化简后结果
    **/
    $time = strtotime($str) - $timezone * 3600;
    return $time;
}

/**
 * 将GMT时间戳格式化为用户自定义时区日期
 *
 * @param  string       $format
 * @param  integer      $time       该参数必须是一个GMT的时间戳
 *
 * @return  string
 */
function local_date($format, $time = NULL){
    if ($time === NULL){
        $time = gmtime();
    }
    elseif ($time <= 0){
        return '';
    }
    return date($format, $time);
}

/**
 * 查询会员的红包金额
 *
 * @access  public
 * @param   integer     $user_id
 * @return  void
 */
function get_user_bonus($user_id = 0){
	
	$CommonModel			=	new CommonModel();
	
    if ($user_id == 0){
        $user_id 			= 	$_SESSION['user_id'];
    }

    $sql 					= 	"SELECT SUM(bt.type_money) AS bonus_value, COUNT(*) AS bonus_count ".
					            "FROM " .'ybr_user_bonus' . " AS ub, ".
					            'ybr_bonus_type' . " AS bt ".
					            "WHERE ub.user_id = '$user_id' AND ub.bonus_type_id = bt.type_id AND ub.order_id = 0";
    $row 					= 	$CommonModel->getRow($sql);

    return $row;
}


/**
 * 生成查询订单的sql
 * @param   string  $type   类型
 * @param   string  $alias  order表的别名（包括.例如 o.）
 * @return  string
 */
function order_query_sql($type = 'finished', $alias = ''){
    /* 已完成订单 */
    if ($type == 'finished'){
        return " AND {$alias}order_status " . db_create_in(array(OS_CONFIRMED, OS_SPLITED)) .
               " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) .
               " AND {$alias}pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " ";
    }
    /* 待发货订单 */
    elseif ($type == 'await_ship'){
        return " AND   {$alias}order_status " .
                 db_create_in(array(OS_CONFIRMED, OS_SPLITED, OS_SPLITING_PART)) .
               " AND   {$alias}shipping_status " .
                 db_create_in(array(SS_UNSHIPPED, SS_PREPARING, SS_SHIPPED_ING)) .
               " AND ( {$alias}pay_status " . db_create_in(array(PS_PAYED, PS_PAYING)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(true)) . ") ";
    }
    /* 待付款订单 */
    elseif ($type == 'await_pay'){
        return " AND   {$alias}order_status " . db_create_in(array(OS_CONFIRMED, OS_SPLITED)) .
               " AND   {$alias}pay_status = '" . PS_UNPAYED . "'" .
               " AND ( {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " OR {$alias}pay_id " . db_create_in(payment_id_list(false)) . ") ";
    }
    /* 未确认订单 */
    elseif ($type == 'unconfirmed'){
        return " AND {$alias}order_status = '" . OS_UNCONFIRMED . "' ";
    }
    /* 未处理订单：用户可操作 */
    elseif ($type == 'unprocessed'){
        return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)) .
               " AND {$alias}shipping_status = '" . SS_UNSHIPPED . "'" .
               " AND {$alias}pay_status = '" . PS_UNPAYED . "' ";
    }
    /* 未付款未发货订单：管理员可操作 */
    elseif ($type == 'unpay_unship'){
        return " AND {$alias}order_status " . db_create_in(array(OS_UNCONFIRMED, OS_CONFIRMED)) .
               " AND {$alias}shipping_status " . db_create_in(array(SS_UNSHIPPED, SS_PREPARING)) .
               " AND {$alias}pay_status = '" . PS_UNPAYED . "' ";
    }
    /* 已发货订单：不论是否付款 */
    elseif ($type == 'shipped'){
        return " AND {$alias}order_status = '" . OS_CONFIRMED . "'" .
               " AND {$alias}shipping_status " . db_create_in(array(SS_SHIPPED, SS_RECEIVED)) . " ";
    }
    else{
        die('函数 order_query_sql 参数错误');
    }
}


/**
 * 创建像这样的查询: "IN('a','b')";
 *
 * @access   public
 * @param    mix      $item_list      列表数组或字符串
 * @param    string   $field_name     字段名称
 *
 */
function db_create_in($item_list, $field_name = ''){
    if (empty($item_list)){
        return $field_name . " IN ('') ";
    }
    else{
        if (!is_array($item_list)){
            $item_list 	= 	explode(',', $item_list);
        }
        $item_list 		= 	array_unique($item_list);
        $item_list_tmp 	= 	'';
        foreach ($item_list AS $item){
            if ($item !== ''){
                $item_list_tmp .= $item_list_tmp ? ",'$item'" : "'$item'";
            }
        }
        if (empty($item_list_tmp)){
            return $field_name . " IN ('') ";
        }
        else{
            return $field_name . ' IN (' . $item_list_tmp . ') ';
        }
    }
}


/**
 * 获取指定 id snatch 活动的结果
 *
 * @access  public
 * @param   int   $id       snatch_id
 *
 * @return  array           array(user_name, bie_price, bid_time, num)
 *                          num通常为1，如果为2表示有2个用户取到最小值，但结果只返回最早出价用户。
 */
function get_snatch_result($id){
	
	$CommonModel					=	new CommonModel();
	
    $sql 							= 	'SELECT u.user_id, u.user_name, u.email, lg.bid_price, lg.bid_time, count(*) as num' .
							            ' FROM ' . 'ybr_snatch_log' . ' AS lg '.
							            ' LEFT JOIN ' . 'ybr_users' . ' AS u ON lg.user_id = u.user_id'.
							            " WHERE lg.snatch_id = '$id'".
							            ' GROUP BY lg.bid_price' .
							            ' ORDER BY num ASC, lg.bid_price ASC, lg.bid_time ASC LIMIT 1';
    $rec 							= 	$CommonModel->getRow($sql);

    if ($rec){
        $rec['bid_time']  			= 	local_date($GLOBALS['_CFG']['time_format'], $rec['bid_time']);
        $rec['formated_bid_price'] 	= 	price_format($rec['bid_price'], false);

        /* 活动信息 */
        $sql 						= 	'SELECT ext_info " .
						               	" FROM ' . 'ybr_goods_activity' .
						               	" WHERE act_id= '$id' AND act_type=" . GAT_SNATCH.
						              	" LIMIT 1";
        $row 						= 	$CommonModel->getOne($sql);
        $info 						= 	unserialize($row);

        if (!empty($info['max_price'])){
            $rec['buy_price'] 		= 	($rec['bid_price'] > $info['max_price']) ? $info['max_price'] : $rec['bid_price'];
        }
        else{
            $rec['buy_price'] 		= 	$rec['bid_price'];
        }

        /* 检查订单 */
        $sql 						= 	"SELECT COUNT(*)" .
						                " FROM " . 'ybr_order_info' .
						                " WHERE extension_code = 'snatch'" .
						                " AND extension_id = '$id'" .
						                " AND order_status " . db_create_in(array(OS_CONFIRMED, OS_UNCONFIRMED));

        $rec['order_count'] 		= 	$CommonModel->getOne($sql);
    }

    return $rec;
}


/**
 * 取得商品优惠价格列表
 *
 * @param   string  $goods_id    商品编号
 * @param   string  $price_type  价格类别(0为全店优惠比率，1为商品优惠价格，2为分类优惠比率)
 *
 * @return  优惠价格列表
 */
function get_volume_price_list($goods_id, $price_type = '1'){
    $volume_price 			= 	array();
    $temp_index   			= 	'0';

    $sql 					= 	"SELECT `volume_number` , `volume_price`".
					           	" FROM " . 'ybr_volume_price' . "".
					           	" WHERE `goods_id` = '" . $goods_id . "' AND `price_type` = '" . $price_type . "'".
					           	" ORDER BY `volume_number`";

    $res 					= 	M()->query($sql);
    
    foreach ($res as $k => $v){
        $volume_price[$temp_index]                 		= 	array();
        $volume_price[$temp_index]['number']       		= 	$v['volume_number'];
        $volume_price[$temp_index]['price']        		= 	$v['volume_price'];
        $volume_price[$temp_index]['format_price'] 		= 	price_format($v['volume_price']);
        $temp_index ++;
    }
    return $volume_price;
}


/**
 * 验证输入的邮件地址是否合法
 *
 * @access  public
 * @param   string      $email      需要验证的邮件地址
 *
 * @return bool
 */
function is_email($user_email){
    $chars 		= 	"/^([a-z0-9+_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,6}\$/i";
    if (strpos($user_email, '@') !== false && strpos($user_email, '.') !== false){
        if (preg_match($chars, $user_email)){
            return true;
        }
        else{
            return false;
        }
    }
    else{
        return false;
    }
}

/**
 * 检查是否为一个合法的时间格式
 *
 * @access  public
 * @param   string  $time
 * @return  void
 */
function is_time($time){
    $pattern = '/[\d]{4}-[\d]{1,2}-[\d]{1,2}\s[\d]{1,2}:[\d]{1,2}:[\d]{1,2}/';
    return preg_match($pattern, $time);
}


/**
 * 分配帮助信息
 *
 * @access  public
 * @return  array
 */
function get_shop_help(){
    $sql 		= 	'SELECT c.cat_id, c.cat_name, c.sort_order, a.article_id, a.title, a.file_url, a.open_type ' .
		            'FROM ' . 'ybr_article' . ' AS a ' .
		            'LEFT JOIN ' .'ybr_article_cat' . ' AS c ' .
		            'ON a.cat_id = c.cat_id WHERE c.cat_type = 5 AND a.is_open = 1 ' .
		            'ORDER BY c.sort_order ASC, a.article_id';
    
    $res 		=	M()->query($sql);

    $arr 		= 	array();
    foreach ($res AS $key => $row){
        //$arr[$row['cat_id']]['cat_id']                       	= 	build_uri('article_cat', array('acid'=> $row['cat_id']), $row['cat_name']);
        $arr[$row['cat_id']]['cat_name']                     	= 	$row['cat_name'];
        $arr[$row['cat_id']]['article'][$key]['article_id']  	= 	$row['article_id'];
        $arr[$row['cat_id']]['article'][$key]['title']       	= 	$row['title'];
        //$arr[$row['cat_id']]['article'][$key]['short_title'] 	= 	$GLOBALS['_CFG']['article_title_length'] > 0 ? sub_str($row['title'], $GLOBALS['_CFG']['article_title_length']) : $row['title'];
        //$arr[$row['cat_id']]['article'][$key]['url']         	= 	$row['open_type'] != 1 ? build_uri('article', array('aid' => $row['article_id']), $row['title']) : trim($row['file_url']);
    }
    return $arr;
}


/**
 *  所有的促销活动信息
 *
 * @access  public
 * @return  array
 */
function get_promotion_info($goods_id = ''){
    $snatch 		= 	array();
    $group 			= 	array();
    $auction 		= 	array();
    $package 		=	array();
    $favourable 	= 	array();
    $CommonModel	=	new CommonModel();

    $gmtime 		= 	gmtime();
    $sql 			= 	'SELECT act_id, act_name, act_type, start_time, end_time FROM ' . 'ybr_goods_activity' . " WHERE is_finished=0 AND start_time <= '$gmtime' AND end_time >= '$gmtime'";
    
    if(!empty($goods_id)){
        $sql 		.= 	" AND goods_id = '$goods_id'";
    }
    $res 			= 	M()->query($sql);
    foreach ($res as $data){
        switch ($data['act_type']){
            case GAT_SNATCH: //夺宝奇兵
                $snatch[$data['act_id']]['act_name']	= 	$data['act_name'];
                //$snatch[$data['act_id']]['url'] 		= 	build_uri('snatch', array('sid' => $data['act_id']));
                $snatch[$data['act_id']]['time'] 		= 	sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $data['start_time']), local_date('Y-m-d', $data['end_time']));
                $snatch[$data['act_id']]['sort'] 		= 	$data['start_time'];
                $snatch[$data['act_id']]['type'] 		= 	'snatch';
                break;

            case GAT_GROUP_BUY: //团购
                $group[$data['act_id']]['act_name'] 	= 	$data['act_name'];
                //$group[$data['act_id']]['url'] 			= 	build_uri('group_buy', array('gbid' => $data['act_id']));
                $group[$data['act_id']]['time'] 		= 	sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $data['start_time']), local_date('Y-m-d', $data['end_time']));
                $group[$data['act_id']]['sort'] 		= 	$data['start_time'];
                $group[$data['act_id']]['type'] 		= 	'group_buy';
                break;

            case GAT_AUCTION: //拍卖
                $auction[$data['act_id']]['act_name'] 	= 	$data['act_name'];
                //$auction[$data['act_id']]['url'] 		= 	build_uri('auction', array('auid' => $data['act_id']));
                $auction[$data['act_id']]['time'] 		= 	sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $data['start_time']), local_date('Y-m-d', $data['end_time']));
                $auction[$data['act_id']]['sort'] 		= 	$data['start_time'];
                $auction[$data['act_id']]['type'] 		= 	'auction';
                break;

            case GAT_PACKAGE: //礼包
                $package[$data['act_id']]['act_name'] 	= 	$data['act_name'];
                //$package[$data['act_id']]['url'] 		= 	'package.php#' . $data['act_id'];
                $package[$data['act_id']]['time'] 		= 	sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $data['start_time']), local_date('Y-m-d', $data['end_time']));
                $package[$data['act_id']]['sort'] 		= 	$data['start_time'];
                $package[$data['act_id']]['type'] 		= 	'package';
                break;
        }
    }

    $user_rank 			= 	',' . $_SESSION['user_rank'] . ',';
    $favourable 		= 	array();
    $sql 				= 	'SELECT act_id, act_range, act_range_ext, act_name, start_time, end_time FROM ' . 'ybr_favourable_activity' . " WHERE start_time <= '$gmtime' AND end_time >= '$gmtime'";
    
    if(!empty($goods_id)){
        $sql 			.=	" AND CONCAT(',', user_rank, ',') LIKE '%" . $user_rank . "%'";
    }    
    $res 				= 	M()->query($sql);

    if(empty($goods_id)){
        foreach ($res as $rows){
            $favourable[$rows['act_id']]['act_name'] 	= 	$rows['act_name'];
            $favourable[$rows['act_id']]['url'] 		= 	'activity.php';
            $favourable[$rows['act_id']]['time'] 		= 	sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $rows['start_time']), local_date('Y-m-d', $rows['end_time']));
            $favourable[$rows['act_id']]['sort'] 		= 	$rows['start_time'];
            $favourable[$rows['act_id']]['type'] 		= 	'favourable';
        }
    }
    else{
        $sql 			= 	"SELECT cat_id, brand_id FROM " . 'ybr_goods' .
           					"WHERE goods_id = '$goods_id'";
        $row 			= 	$CommonModel->getRow($sql);
        $category_id 	= 	$row['cat_id'];
        $brand_id 		=	$row['brand_id'];

        foreach ($res as $rows){
            if ($rows['act_range'] == FAR_ALL){
                $favourable[$rows['act_id']]['act_name'] 	= 	$rows['act_name'];
                $favourable[$rows['act_id']]['url'] 		= 	'activity.php';
                $favourable[$rows['act_id']]['time'] 		= 	sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $rows['start_time']), local_date('Y-m-d', $rows['end_time']));
                $favourable[$rows['act_id']]['sort'] 		= 	$rows['start_time'];
                $favourable[$rows['act_id']]['type'] 		= 	'favourable';
            }
            elseif ($rows['act_range'] == FAR_CATEGORY){
                /* 找出分类id的子分类id */
                $id_list 									= 	array();
                $raw_id_list 								= 	explode(',', $rows['act_range_ext']);
                foreach ($raw_id_list as $id){
                    $id_list 								= 	array_merge($id_list, array_keys(cat_list($id, 0, false)));
                }
                $ids 										= 	join(',', array_unique($id_list));

                if (strpos(',' . $ids . ',', ',' . $category_id . ',') !== false){
                    $favourable[$rows['act_id']]['act_name'] 	= 	$rows['act_name'];
                    $favourable[$rows['act_id']]['url'] 		= 	'activity.php';
                    $favourable[$rows['act_id']]['time'] 		= 	sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $rows['start_time']), local_date('Y-m-d', $rows['end_time']));
                    $favourable[$rows['act_id']]['sort'] 		= 	$rows['start_time'];
                    $favourable[$rows['act_id']]['type'] 		= 	'favourable';
                }
            }
            elseif ($rows['act_range'] == FAR_BRAND){
                if (strpos(',' . $rows['act_range_ext'] . ',', ',' . $brand_id . ',') !== false){
                    $favourable[$rows['act_id']]['act_name'] 	= 	$rows['act_name'];
                    $favourable[$rows['act_id']]['url'] 		= 	'activity.php';
                    $favourable[$rows['act_id']]['time'] 		= 	sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $rows['start_time']), local_date('Y-m-d', $rows['end_time']));
                    $favourable[$rows['act_id']]['sort'] 		= 	$rows['start_time'];
                    $favourable[$rows['act_id']]['type'] 		= 	'favourable';
                }
            }
            elseif ($rows['act_range'] == FAR_GOODS){
                if (strpos(',' . $rows['act_range_ext'] . ',', ',' . $goods_id . ',') !== false){
                    $favourable[$rows['act_id']]['act_name'] 	= 	$rows['act_name'];
                    $favourable[$rows['act_id']]['url'] 		= 	'activity.php';
                    $favourable[$rows['act_id']]['time'] 		= 	sprintf($GLOBALS['_LANG']['promotion_time'], local_date('Y-m-d', $rows['start_time']), local_date('Y-m-d', $rows['end_time']));
                    $favourable[$rows['act_id']]['sort'] 		= 	$rows['start_time'];
                    $favourable[$rows['act_id']]['type'] 		= 	'favourable';
                }
            }
        }
    }

    $sort_time 			= 	array();
    $arr 				= 	array_merge($snatch, $group, $auction, $package, $favourable);
    foreach($arr as $key => $value){
        $sort_time[] 	= 	$value['sort'];
    }
    array_multisort($sort_time, SORT_NUMERIC, SORT_DESC, $arr);

    return $arr;
}


/**
 * 获得商品的详细信息
 *
 * @access  public
 * @param   integer     $goods_id
 * @return  void
 */
function get_goods_info($goods_id){
	
	$CommonModel	=	new CommonModel();
	
    $time 			= 	gmtime();
    $sql 			= 	'SELECT g.*, c.measure_unit, b.brand_id, b.brand_name AS goods_brand, m.type_money AS bonus_money, ' .
		                'IFNULL(AVG(r.comment_rank), 0) AS comment_rank, ' .
		                "IFNULL(mp.user_price, g.shop_price * '$_SESSION[discount]') AS rank_price " .
			            'FROM ' . 'ybr_goods' . ' AS g ' .
			            'LEFT JOIN ' . 'ybr_category' . ' AS c ON g.cat_id = c.cat_id ' .
			            'LEFT JOIN ' . 'ybr_brand' . ' AS b ON g.brand_id = b.brand_id ' .
			            'LEFT JOIN ' . 'ybr_comment' . ' AS r '.
                		'ON r.id_value = g.goods_id AND comment_type = 0 AND r.parent_id = 0 AND r.status = 1 ' .
            			'LEFT JOIN ' . 'ybr_bonus_type' . ' AS m ' .
                		"ON g.bonus_type_id = m.type_id AND m.send_start_date <= '$time' AND m.send_end_date >= '$time'" .
            			" LEFT JOIN " . 'ybr_member_price' . " AS mp ".
                    	"ON mp.goods_id = g.goods_id AND mp.user_rank = '$_SESSION[user_rank]' ".
            			"WHERE g.goods_id = '$goods_id' AND g.is_delete = 0 " .
            			"GROUP BY g.goods_id";
    
    $row 			= 	$CommonModel->getRow($sql);

    if ($row !== false){
        /* 用户评论级别取整 */
        $row['comment_rank']  		= 	ceil($row['comment_rank']) == 0 ? 5 : ceil($row['comment_rank']);

        /* 获得商品的销售价格 */
        $row['market_price']        = 	price_format($row['market_price']);
        $row['shop_price_formated'] =	price_format($row['shop_price']);

        /* 修正促销价格 */
        if ($row['promote_price'] > 0){
            $promote_price 			= 	bargain_price($row['promote_price'], $row['promote_start_date'], $row['promote_end_date']);
        }
        else{
            $promote_price 			= 	0;
        }

        /* 处理商品水印图片 */
        $watermark_img = '';

        if ($promote_price != 0){
            $watermark_img 			= 	"watermark_promote";
        }
        elseif ($row['is_new'] != 0){
            $watermark_img 			= 	"watermark_new";
        }
        elseif ($row['is_best'] != 0){
            $watermark_img 			= 	"watermark_best";
        }
        elseif ($row['is_hot'] != 0){
            $watermark_img 			= 	'watermark_hot';
        }

        if ($watermark_img != ''){
            $row['watermark_img'] 	=  	$watermark_img;
        }

        $row['promote_price_org'] 	=  	$promote_price;
        $row['promote_price'] 		= 	price_format($promote_price);

        /* 修正重量显示 */
        $row['goods_weight'] 	 	= 	(intval($row['goods_weight']) > 0) ? $row['goods_weight'] . $GLOBALS['_LANG']['kilogram'] : ($row['goods_weight'] * 1000) . $GLOBALS['_LANG']['gram'];

        /* 修正上架时间显示 */
        $row['add_time']      		= 	local_date($GLOBALS['_CFG']['date_format'], $row['add_time']);

        /* 促销时间倒计时 */
        $time 						= 	gmtime();
        if ($time >= $row['promote_start_date'] && $time <= $row['promote_end_date']){
             $row['gmt_end_time']  	= 	$row['promote_end_date'];
        }
        else{
            $row['gmt_end_time']	= 	0;
        }

        /* 是否显示商品库存数量 */
        $row['goods_number']  		= 	($GLOBALS['_CFG']['use_storage'] == 1) ? $row['goods_number'] : '';

        /* 修正积分：转换为可使用多少积分（原来是可以使用多少钱的积分） */
        $row['integral']      		= 	$GLOBALS['_CFG']['integral_scale'] ? round($row['integral'] * 100 / $GLOBALS['_CFG']['integral_scale']) : 0;

        /* 修正优惠券 */
        $row['bonus_money']   		= 	($row['bonus_money'] == 0) ? 0 : price_format($row['bonus_money'], false);

        return $row;
    }
    else{
        return false;
    }
}

/**
 * 格式化商品价格
 *
 * @access  public
 * @param   float   $price  商品价格
 * @return  string
 */
function price_format($price, $change_price = true){
    if($price===''){
     	$price=0;
    }
    if ($change_price){
        switch (1){
            case 0:
                $price = number_format($price, 2, '.', '');
                break;
            case 1: // 保留不为 0 的尾数
                $price = preg_replace('/(.*)(\\.)([0-9]*?)0+$/', '\1\2\3', number_format($price, 2, '.', ''));
                
                if (substr($price, -1) == '.'){
                    $price = substr($price, 0, -1);
                }
                break;
            case 2: // 不四舍五入，保留1位
                $price = substr(number_format($price, 2, '.', ''), 0, -1);
                break;
            case 3: // 直接取整
                $price = intval($price);
                break;
            case 4: // 四舍五入，保留 1 位
                $price = number_format($price, 1, '.', '');
                break;
            case 5: // 先四舍五入，不保留小数
                $price = round($price);
                break;
        }
    }
    else{
        $price = number_format($price, 2, '.', '');
    }
    //return sprintf($GLOBALS['_CFG']['currency_format'], $price);
    return $price;
}


/**
 * 重新获得商品图片与商品相册的地址
 *
 * @param int $goods_id 商品ID
 * @param string $image 原商品相册图片地址
 * @param boolean $thumb 是否为缩略图
 * @param string $call 调用方法(商品图片还是商品相册)
 * @param boolean $del 是否删除图片
 *
 * @return string   $url
 */
function get_image_path($goods_id, $image='', $thumb=false, $call='goods', $del=false){
    $url 	= 	empty($image) ? $GLOBALS['_CFG']['no_picture'] : $image;
    return $url;
}

/**
 * 获得指定分类下所有底层分类的ID
 *
 * @access  public
 * @param   integer     $cat        指定的分类ID
 * @return  string
 */
function get_children($cat = 0){
    return 'g.cat_id ' . db_create_in(array_unique(array_merge(array($cat), array_keys(cat_list($cat, 0, false)))));
}

/**
 *
 * 是否存在规格
 *
 * @access      public
 * @param       array       $goods_attr_id_array        一维数组
 *
 * @return      string
 */
function is_spec($goods_attr_id_array, $sort = 'asc'){
    if (empty($goods_attr_id_array)){
        return $goods_attr_id_array;
    }

    //重新排序
    $sql 		= 	"SELECT a.attr_type, v.attr_value, v.goods_attr_id
		            FROM " . 'ybr_attribute' . " AS a
		            LEFT JOIN " .'ybr_goods_attr' . " AS v
                	ON v.attr_id = a.attr_id
                	AND a.attr_type = 1
            		WHERE v.goods_attr_id " . db_create_in($goods_attr_id_array) . "
            		ORDER BY a.attr_id $sort";
    $row 		= 	M()->query($sql);

    $return_arr = 	array();
    foreach ($row as $value){
        $return_arr['sort'][]   						= 	$value['goods_attr_id'];
        $return_arr['row'][$value['goods_attr_id']]    	= 	$value;
    }

    if(!empty($return_arr)){
        return true;
    }
    else{
        return false;
    }
}


/**
 * 查询购物车（订单id为0）或订单中是否有实体商品
 * @param   int     $order_id   订单id
 * @param   int     $flow_type  购物流程类型
 * @return  bool
 */
function exist_real_goods($order_id = 0, $flow_type = CART_GENERAL_GOODS){
	$CommonModel	=	new CommonModel();
    if ($order_id <= 0){
        $sql = "SELECT COUNT(*) FROM " . 'ybr_cart' .
                " WHERE session_id = '" . SESS_ID . "' AND is_real = 1 " .
                "AND rec_type = '$flow_type'";
    }
    else{
        $sql = "SELECT COUNT(*) FROM " . 'ybr_order_goods' .
                " WHERE order_id = '$order_id' AND is_real = 1";
    }
    // 测试
    //echo $sql;
    
    return $CommonModel->getOne($sql) > 0;
}


/**
 * 记录帐户变动
 * @param   int     $user_id        用户id
 * @param   float   $user_money     可用余额变动
 * @param   float   $frozen_money   冻结余额变动
 * @param   int     $rank_points    等级积分变动
 * @param   int     $pay_points     消费积分变动
 * @param   string  $change_desc    变动说明
 * @param   int     $change_type    变动类型：参见常量文件
 * @return  void
 */
function log_account_change($user_id, $user_money = 0, $frozen_money = 0, $rank_points = 0, $pay_points = 0, $change_desc = '', $change_type = ACT_OTHER){
    
    $CommonModel	=	new CommonModel();
    /* 插入帐户变动记录 */
    $account_log = array(
        'user_id'       => $user_id,
        'user_money'    => $user_money,
        'frozen_money'  => $frozen_money,
        'rank_points'   => $rank_points,
        'pay_points'    => $pay_points,
        'change_time'   => gmtime(),
        'change_desc'   => $change_desc,
        'change_type'   => $change_type
    );
    //$GLOBALS['db']->autoExecute('ybr_account_log'), $account_log, 'INSERT');
	$CommonModel->autoExecute('account_log', $account_log, 'INSERT');
    /* 更新用户信息 */
    $sql = "UPDATE " . 'ybr_users' .
            " SET user_money = user_money + ('$user_money')," .    	// 原来账户的金额加上返回的金额
            " frozen_money = frozen_money + ('$frozen_money')," .	// 冻结变动
            " rank_points = rank_points + ('$rank_points')," .		// 等级积分变动
            " pay_points = pay_points + ('$pay_points')" .			// 消费积分变动
            " WHERE user_id = '$user_id' LIMIT 1";					
    //$GLOBALS['db']->query($sql);
    M()->query($sql);
}


/**
 * 改变订单中商品库存
 * @param   int     $order_id   订单号
 * @param   bool    $is_dec     是否减少库存
 * @param   bool    $storage     减库存的时机，1，下订单时；0，发货时；
 */
function change_order_goods_storage($order_id, $is_dec = true, $storage = 0){
    /* 查询订单商品信息 */
    switch ($storage){
        case 0 :
            $sql = "SELECT goods_id, SUM(send_number) AS num, MAX(extension_code) AS extension_code, product_id FROM " . 'ybr_order_goods' .
                    " WHERE order_id = '$order_id' AND is_real = 1 GROUP BY goods_id, product_id";
        break;

        case 1 :
            $sql = "SELECT goods_id, SUM(goods_number) AS num, MAX(extension_code) AS extension_code, product_id FROM " . 'ybr_order_goods' .
                    " WHERE order_id = '$order_id' AND is_real = 1 GROUP BY goods_id, product_id";
        break;
    }
	
    $res = M()->query($sql);
    foreach($res as $row){
    	if ($row['extension_code'] != "package_buy"){
            if ($is_dec){// 减少库存
                change_goods_storage($row['goods_id'], $row['product_id'], - $row['num']);
            }
            else{// 增加库存
                change_goods_storage($row['goods_id'], $row['product_id'], $row['num']);
            }
            M()->query($sql);
        }
        else{
            $sql = "SELECT goods_id, goods_number" .
                   " FROM " . 'ybr_package_goods' .
                   " WHERE package_id = '" . $row['goods_id'] . "'";
            $res_goods = M()->query($sql);
            foreach($res_goods as $row_goods){
            	$sql = 	"SELECT is_real" .
                  	 	" FROM " . 'ybr_goods' .
                  	 	" WHERE goods_id = '" . $row_goods['goods_id'] . "'";
                $real_goods = M()->query($sql);
                $is_goods = $real_goods[0];

                if ($is_dec){
                    change_goods_storage($row_goods['goods_id'], $row['product_id'], - ($row['num'] * $row_goods['goods_number']));
                }
                elseif ($is_goods['is_real']){
                    change_goods_storage($row_goods['goods_id'], $row['product_id'], ($row['num'] * $row_goods['goods_number']));
                }
            }
        }
    }
}


/**
 * 将支付LOG插入数据表
 *
 * @access  public
 * @param   integer     $id         订单编号
 * @param   float       $amount     订单金额
 * @param   integer     $type       支付类型
 * @param   integer     $is_paid    是否已支付
 *
 * @return  int
 */
function insert_pay_log($id, $amount, $type = PAY_SURPLUS, $is_paid = 0){
	$CommonModel	=	new CommonModel();
    $sql 			= 	'INSERT INTO ' . 'ybr_pay_log'." (order_id, order_amount, order_type, is_paid)" . " VALUES  ('$id', '$amount', '$type', '$is_paid')";
    $CommonModel->query($sql);
    return $CommonModel->insert_id();
}

/**
 * 获得指定国家的所有省份
 *
 * @access      public
 * @param       int     country    国家的编号
 * @return      array
 */
function get_regions($type = 0, $parent = 0){
    $sql 		= 	"SELECT region_id, region_name FROM `ybr_region` WHERE region_type = '{$type}' AND parent_id = '{$parent}'";
    return M()->query($sql);
}

/**
 * 获得指定地区名称
 *
 * @access      public
 * @param       int     country    国家的编号
 * @return      array
 */
function get_regions_name($type = 0, $parent = 0){ 
    $data =  M("Region")->field("region_name")->where("region_type = '$type' AND region_id = '$parent'")->find();
    return empty($data['region_name']) ? "" : $data['region_name'];
}

/**
 * 自动生成用户名
 * Enter description here ...
 * @param $length
 */
function generate_username( $length = 6 ) {    
	// 密码字符集，可任意添加你需要的字符     
	$chars 		= 	'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';    
	$password 	= 	'';    
	for ( $i = 0; $i < $length; $i++ ){
		// 这里提供两种字符获取方式    
		// 第一种是使用substr 截取$chars中的任意一位字符；    
		// 第二种是取字符数组$chars 的任意元素    
		// $password .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);    
		$password .= $chars[ mt_rand(0, strlen($chars) - 1) ];    
	}    
	return 'ybr_' . $password;    
}  






















